﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using c_work.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Work.Models;

namespace Work.Controllers
{
	[Route("[Controller]/[Action]")]
	[ApiController]
	public class BlogsController : Controller
	{
		private readonly DBContext _context;

		public BlogsController(DBContext context)
		{
			_context = context;
		}

		/// <summary>
		/// 热榜文章
		/// </summary>
		/// <param name="typeId"></param>
		/// <returns></returns>
		[HttpGet]
		[NoSign]
		public async Task<string> HostList()
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var list = await _context.Blogs.ToListAsync();
			var data = list.OrderByDescending(e => e.LikeCount).Take(4);
			dic.Add("data", data);
			dic.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 根据类型获取文章
		/// </summary>
		/// <param name="typeId"></param>
		/// <returns></returns>
		[HttpGet]
		[NoSign]
		public async Task<string> Index(int typeId)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			var list = await _context.Blogs.ToListAsync();
			var data = list.Where(i => i.BlogTypeId == typeId).OrderByDescending(e=>e.CreateAt);
			dic.Add("data", data);
			dic.Add("code", 0);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		// GET: Blogs/Details/5
		public async Task<IActionResult> Details(int? id)
		{
			if (id == null)
			{
				return NotFound();
			}

			var blog = await _context.Blogs
				.FirstOrDefaultAsync(m => m.Id == id);
			if (blog == null)
			{
				return NotFound();
			}

			return View(blog);
		}

		// GET: Blogs/Create
		public IActionResult Create()
		{
			return View();
		}

		/// <summary>
		/// 发表文章
		/// </summary>
		/// <param name="bg"></param>
		/// <returns></returns>
		[HttpPost]
		public  string Create(Blog bg)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			Blog blog = new Blog()
			{
				BlogTypeId = bg.BlogTypeId,
				Title = bg.Title,
				Email = bg.Email,
				Content = bg.Content,
				LikeCount = 0,
				Pic = bg.Pic,
				CreateAt = DateTime.Now.ToString("yyyy-MM-dd").ToString(),
				UpdateAt = "0000-00-00"
			};
			try
			{
				_context.Add(blog);
				 _context.SaveChangesAsync();
				dic.Add("code", 0);
				dic.Add("msg", "文章发表成功");
			}
			catch (Exception e)
			{
				Exception u = e;
				Console.WriteLine(u);
				_context.Add(blog);
				 _context.SaveChangesAsync();
				dic.Add("code", 0);
				dic.Add("msg", "失败：" + e);
			}
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		/// <summary>
		/// 点赞
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task<string> Like(int id)
		{
			Dictionary<string, object> dic = new Dictionary<string, object>();
			Blog blog = await _context.Blogs.FindAsync(id);
			blog.LikeCount++;
			_context.Update(blog);
			await _context.SaveChangesAsync();
			dic.Add("code", 0);
			dic.Add("data", blog);
			return Newtonsoft.Json.JsonConvert.SerializeObject(dic);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<IActionResult> Edit(int id, [Bind("Id,BlogTypeId,Email,Content,LikeCount,Pic,CreateAt,UpdateAt")] Blog blog)
		{
			if (id != blog.Id)
			{
				return NotFound();
			}

			if (ModelState.IsValid)
			{
				try
				{
					_context.Update(blog);
					await _context.SaveChangesAsync();
				}
				catch (DbUpdateConcurrencyException)
				{
					if (!BlogExists(blog.Id))
					{
						return NotFound();
					}
					else
					{
						throw;
					}
				}
				return RedirectToAction(nameof(Index));
			}
			return View(blog);
		}

		// GET: Blogs/Delete/5
		public async Task<IActionResult> Delete(int? id)
		{
			if (id == null)
			{
				return NotFound();
			}

			var blog = await _context.Blogs
				.FirstOrDefaultAsync(m => m.Id == id);
			if (blog == null)
			{
				return NotFound();
			}

			return View(blog);
		}

		// POST: Blogs/Delete/5
		[HttpPost, ActionName("Delete")]
		[ValidateAntiForgeryToken]
		public async Task<IActionResult> DeleteConfirmed(int id)
		{
			var blog = await _context.Blogs.FindAsync(id);
			_context.Blogs.Remove(blog);
			await _context.SaveChangesAsync();
			return RedirectToAction(nameof(Index));
		}

		private bool BlogExists(int id)
		{
			return _context.Blogs.Any(e => e.Id == id);
		}
	}
}
